//https://leetcode.cn/problems/course-schedule-ii/?envType=daily-question&envId=2023-09-10

class Solution {    //CV
public:
    vector<int> findOrder(int numCourses, vector<vector<int>>& prerequisites) {
        vector<int> pre_courses(numCourses);//每个课程的入度
        vector<vector<int>> next_courses(numCourses);//存储以该课程为前置的课程
        for(int i=0;i<prerequisites.size();i++)
        {
            pre_courses[prerequisites[i][1]]++;//入度++
            next_courses[prerequisites[i][0]].push_back(prerequisites[i][1]);
        }
        queue<int> can_study;
        for(int i=0;i<numCourses;i++)
        {
            if(pre_courses[i]==0)
            {
                can_study.push(i);
            }
        }
        int count=0;
        vector<int>ans;
        while(!can_study.empty())
        {
            int now_study=can_study.front();
            ans.push_back(now_study);
            can_study.pop();
            count++;
            for(int i=0;i<next_courses[now_study].size();i++)
            {
                pre_courses[next_courses[now_study][i]]--;
                if(pre_courses[next_courses[now_study][i]]==0)
                    can_study.push(next_courses[now_study][i]);
            }
        }
        reverse(ans.begin(),ans.end());
        if(count==numCourses)
        return ans;
        else return {};
    }
};